import XEUtils from 'xe-utils'


function getProps ({ $table }, { props }, defaultProps) {
  return XEUtils.assign($table.vSize ? { size: $table.vSize } : {}, defaultProps, props)
}
function getCellEvents (renderOpts, params) {
  let { name, events } = renderOpts
  let { $table } = params
  let type = 'change'
  switch (name) {
    case 'ElAutocomplete':
      type = 'select'
      break
    case 'ElInput':
    case 'ElInputNumber':
      type = 'input'
      break
  }
  let on = {
    [type]: (evnt) => {
      $table.updateStatus(params)
      if (events && events[type]) {
        events[type](params, evnt)
      }
    }
  }
  if (events) {
    return XEUtils.assign({}, XEUtils.objectMap(events, (cb) => function (...args) {
      cb.apply(null, [params].concat.apply(params, args))
    }), on)
  }
  return on
}
export function createEditRender(defaultProps) {
  return function (h, renderOpts, params) {
  let { row, column } = params
  let { attrs } = renderOpts
  let props = getProps(params, renderOpts, defaultProps)
  return [
    h('el-color-picker', {
      props,
      attrs,
      model: {
        value: XEUtils.get(row, column.property),
        predefine: XEUtils.get(row, column.property),
        callback (value) {
          console.log('value',value)
          XEUtils.set(row, column.property, value)
        }
      },
      on: getCellEvents(renderOpts, params)
    })
  ]}
}
export function createFormItemRender (defaultProps) {
  return function (h, renderOpts, params, context) {
    let { data, property } = params
    let { name } = renderOpts
    let { attrs } = renderOpts
    let props = getFormProps(params, renderOpts, defaultProps)
    return [
      h(name, {
        attrs,
        props,
        model: {
          value: XEUtils.get(data, property),
          callback (value) {
            XEUtils.set(data, property, value)
          }
        },
        on: getFormEvents(renderOpts, params)
      })
    ]
  }
}

function getFormProps ({ $form }, { props }, defaultProps) {
  return XEUtils.assign($form.vSize ? { size: $form.vSize } : {}, defaultProps, props)
}

function getFormEvents (renderOpts, params) {
  let { events } = renderOpts
  let { $form } = params
  let type = 'change'
  switch (name) {
    case 'ElAutocomplete':
      type = 'select'
      break
    case 'ElInput':
    case 'ElInputNumber':
      type = 'input'
      break
  }
  let on = {
    [type]: (evnt) => {
      $form.updateStatus(params)
      if (events && events[type]) {
        events[type](params, evnt)
      }
    }
  }
  if (events) {
    return XEUtils.assign({}, XEUtils.objectMap(events, (cb) => function (...args) {
      cb.apply(null, [params].concat.apply(params, args))
    }), on)
  }
  return on
}
export function cellText (h, cellValue) {
  return ['' + (isEmptyValue(cellValue) ? '' : cellValue)]
}
function isEmptyValue (cellValue) {
  return cellValue === null || cellValue === undefined || cellValue === ''
}